package com.example.demo;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class BeanInstantiationTimeTracker implements InstantiationAwareBeanPostProcessor {
    private final Map<String, Long> startTimes = new ConcurrentHashMap<>();

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        Long startTime = startTimes.remove(beanName);
        if (startTime != null) {
            long cost = System.currentTimeMillis() - startTime;
            if (cost > 100) {

                System.out.println("-- postProcessAfterInstantiation - " + beanName + ": " + cost + "ms");
            }
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {

        startTimes.put(beanName, System.currentTimeMillis());

        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
    }

}